<template>
  <el-form ref="form" :model="data" :rules="rules" label-width="100px">
    <el-form-item label="点位名称" prop="title">
      <el-input v-model.trim="data.title" placeholder="请填写点位名称" />
    </el-form-item>
    <el-form-item label="所属项目" prop="project_id">
      <el-select v-model="data.project_id" placeholder="请选择所属项目" clearable @change="select_project" class="filter-item">
        <el-option v-for="(project,index) in project_list" :key="index" :label="project.title" :value="project.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="所属建筑" prop="building_id">
      <el-select v-model="data.building_id" placeholder="请选择所属建筑" @change="select_building" clearable class="filter-item">
        <el-option v-for="(building,index) in building_list" :key="index" :label="building.title" :value="building.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="所属楼层" prop="floor_id">
      <el-select v-model.trim="data.floor_id" placeholder="请选择所属楼层" clearable class="filter-item">
        <el-option v-for="(floor,index) in floor_list" :key="index" :label="floor.title" :value="floor.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="排序" prop="sort">
      <el-input-number v-model="data.sort" :min="1" :max="10" label="排序"></el-input-number>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" :disabled="$store.state.settings.ajaxButton" @click="submit">更新</el-button>
      <el-button type="danger" @click="handleCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { edit, detail } from '@/api/inspectionpoints'
import { getToken } from '@/utils/auth'
import { commonApi } from '@/api/common'

export default {
  name: 'inspectionpointsEdit',
  props: {
    item: {
      type: Object,
      default: () => {
        return {}
      }
    },
    project_list: {
      type: Array,
      default: () => {
        return []
      }
    },
  },
  data() {
    return {
      loading: false,
      building_list: [],
      floor_list: [],
      rules: {
        title: [ 
          { required: true, message: "请输入点位名称", trigger: "blur" }
        ], 
        project_id: [ 
          { required: true, message: "请选择所属项目", trigger: "change" }
        ], 
      },
      data: {
        id: '',
        title: '',
        project_id: '',
        building_id: '',
        floor_id: '',
        sort: '',
      }
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    // 加载点位详情
    loadData() {
      if (!this.item.id) {
        this.$message.error('点位ID不存在')
        return
      }

      this.loading = true
      detail(this.item.id).then(response => {
        this.loading = false
        const pointData = response.data
        
        // 填充表单数据
        this.data = {
          id: pointData.id,
          title: pointData.title,
          project_id: pointData.project_id,
          building_id: pointData.building_id,
          floor_id: pointData.floor_id,
          sort: pointData.sort || 1,
        }

        // 如果已有项目ID，加载对应的建筑列表
        if (pointData.project_id) {
          this.loadBuildings(pointData.project_id)
        }

        // 如果已有建筑ID，加载对应的楼层列表
        if (pointData.building_id) {
          this.loadFloors(pointData.building_id)
        }

      }).catch(error => {
        this.loading = false
        console.error('获取点位详情失败:', error)
        this.$message.error('获取点位详情失败')
      })
    },

    // 加载建筑列表
    loadBuildings(projectId) {
      commonApi.get_building({ project_id: projectId }).then(response => {
        this.building_list = response.data
      }).catch(error => {
        console.error('获取建筑列表失败:', error)
        this.building_list = []
      })
    },

    // 加载楼层列表
    loadFloors(buildingId) {
      commonApi.get_floor({ building_id: buildingId }).then(response => {
        this.floor_list = response.data
      }).catch(error => {
        console.error('获取楼层列表失败:', error)
        this.floor_list = []
      })
    },

    // 项目选择变化
    select_project(value) {
      console.log('项目选择:', value)
      
      // 清空下级选择
      this.data.building_id = ''
      this.data.floor_id = ''
      this.building_list = []
      this.floor_list = []

      if (!value) {
        return
      }
      
      this.loadBuildings(value)
    },

    // 建筑选择变化
    select_building(value) {
      console.log('建筑选择:', value)
      
      // 清空楼层选择
      this.data.floor_id = ''
      this.floor_list = []

      if (!value) {
        return
      }
      
      this.loadFloors(value)
    },

    // 提交更新
    submit() {
      const thiz = this

      this.$refs.form.validate(valid => {
        if (!valid) {
          return false
        }

        this.$store.commit('settings/SET_AJAX_BUTTON', true)
        
        edit({
          id: this.data.id,
          title: this.data.title,
          project_id: this.data.project_id,
          building_id: this.data.building_id,
          floor_id: this.data.floor_id,
          sort: this.data.sort,
        }).then(response => {
          this.$message({
            message: '更新成功',
            type: 'success',
            duration: 1500,
            onClose() {
              thiz.$store.commit('settings/SET_AJAX_BUTTON', false)
              thiz.item.dialogVisible = false
              // 触发更新成功事件，通知父组件刷新数据
              thiz.$emit('update-success')
            }
          })
        }).catch(error => {
          this.$store.commit('settings/SET_AJAX_BUTTON', false)
          console.error('更新失败:', error)
        })
      })
    },

    // 取消编辑
    handleCancel() {
      this.item.dialogVisible = false
    }
  }
}
</script>